﻿using System;
using System.Collections.Generic;
using System.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;

using System.Windows.Media.Imaging;
using DevExpress.Xpf.Core;
using System.Windows.Browser;
using System.IO;

namespace Cinser.Common.Silverlight.Controls
{
    public partial class VedioPlayer : DXWindow
    {
        private DispatcherTimer _timerPlay;
        //实际应用中，以下字符串可通过wcf调用获得
        private string _medialist = "[{src:'http://task.24city.com/video/01.mp4',name:'苹果王手机第1段'},{src:'http://task.24city.com/video/02.mp4',name:'苹果王手机第2段'},{src:'http://task.24city.com/video/03.mp4',name:'苹果王手机第3段'},{src:'http://task.24city.com/video/04.mp4',name:'蔡依林-柠檬草的味道'},{src:'http://task.24city.com/video/05.mp4',name:'我也不知道是啥'},{src:'http://task.24city.com/video/06.mp4',name:'游戏宣传片段'}]";
        List<MediaItem> _listMedia = null;
        int _currentIndex = -1;//正在播放的元素索引

        public VedioPlayer()
        {
            InitializeComponent();
            //解析Json
            JsonValue _jsValue = JsonArray.Parse(_medialist);
            if (_jsValue.Count > 0)
            {
                _listMedia = new List<MediaItem>(_jsValue.Count);
                for (int i = 0; i < _jsValue.Count; i++)
                {
                    _listMedia.Add(new MediaItem() { src = _jsValue[i]["src"], name = _jsValue[i]["name"] });
                }
                _currentIndex = 0;//默认从第一个开始播放
                media.Source = new Uri(_listMedia[_currentIndex].src);
                cboList.ItemsSource = _listMedia;
                cboList.DisplayMemberPath = "name";
                cboList.SelectedIndex = _currentIndex;

                this._timerPlay = new DispatcherTimer();
                this._timerPlay.Interval = new TimeSpan(0, 0, 0, 0, 100);
                this._timerPlay.Tick += new EventHandler(timer_Tick);
                this._timerPlay.Start();
            }

            Application.Current.Host.Content.FullScreenChanged += new EventHandler(Content_FullScreenChanged);
        }
        /**/
        /// <summary>
        /// timer触发时，设置进度条与播放时间同步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void timer_Tick(object sender, EventArgs e)
        {
            this.sliderProgress.Maximum = this.media.NaturalDuration.TimeSpan.TotalSeconds;
            this.sliderProgress.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(sliderProgress_ValueChanged);
            this.sliderProgress.Value = this.media.Position.TotalSeconds;
            this.sliderProgress.ValueChanged += new RoutedPropertyChangedEventHandler<double>(sliderProgress_ValueChanged);
            this.txtTime.Text = media.Position.Hours.ToString().PadLeft(2, '0') + ":" + media.Position.Minutes.ToString().PadLeft(2, '0') + ":" + media.Position.Seconds.ToString().PadLeft(2, '0') + "/" + media.NaturalDuration.TimeSpan.Hours.ToString().PadLeft(2, '0') + ":" + media.NaturalDuration.TimeSpan.Minutes.ToString().PadLeft(2, '0') + ":" + media.NaturalDuration.TimeSpan.Seconds.ToString().PadLeft(2, '0');
        }
        /**/
        /// <summary>
        /// 显示播放状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Media_State_Changed(object sender, EventArgs e)
        {

            if (_currentIndex >= 0)
            {
                MediaItem _currentMedia = _listMedia[_currentIndex];
                switch (media.CurrentState)
                {
                    case System.Windows.Media.MediaElementState.AcquiringLicense:
                        txtProgress.Text = "加载许可证";

                        break;
                    case System.Windows.Media.MediaElementState.Buffering:
                        txtProgress.Text = "缓冲中";
                        break;
                    case System.Windows.Media.MediaElementState.Closed:
                        txtProgress.Text = "已关闭";
                        break;
                    case System.Windows.Media.MediaElementState.Individualizing:
                        txtProgress.Text = "加载个性化设置";
                        break;
                    case System.Windows.Media.MediaElementState.Opening:
                        txtProgress.Text = "加载中";
                        break;
                    case System.Windows.Media.MediaElementState.Paused:
                        txtProgress.Text = "已暂停";
                        break;
                    case System.Windows.Media.MediaElementState.Playing:
                        txtProgress.Text = "正在播放";
                        //预选缓冲下一段视频(不过在实际测试中，感觉这么干没啥明显效果，欢迎大家共同探讨如何提前缓冲下一段视频)
                        if (_currentIndex + 1 > _listMedia.Count - 1)
                        {
                            mediaBuffer.Source = new Uri(_listMedia[0].src);
                        }
                        else
                        {
                            mediaBuffer.Source = new Uri(_listMedia[_currentIndex + 1].src);
                        }

                        break;
                    case System.Windows.Media.MediaElementState.Stopped:
                        txtProgress.Text = "已停止";
                        break;
                    default:
                        break;
                }
            }
        }

        /**/
        /// <summary>
        /// 停止播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopMedia(object sender, System.Windows.RoutedEventArgs e)
        {
            media.Stop();
            btnPlay.Content = ">";
        }

        /**/
        /// <summary>
        /// 播放/暂停
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PlayMedia(object sender, System.Windows.RoutedEventArgs e)
        {
            if (media.CurrentState == System.Windows.Media.MediaElementState.Paused || media.CurrentState == System.Windows.Media.MediaElementState.Stopped)
            {
                media.Play();
                btnPlay.Content = "||";
                canvas_Pause.Visibility = Visibility.Collapsed;

            }
            else
            {
                media.Pause();
                btnPlay.Content = ">";
                canvas_Pause.Visibility = Visibility.Visible;
            }

        }
        /**/
        /// <summary>
        /// 一段播放完毕后，自动跳到下一段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void media_MediaEnded(object sender, System.Windows.RoutedEventArgs e)
        {
            _currentIndex++;
            if (_currentIndex > _listMedia.Count - 1)
            {
                _currentIndex = 0;
            }
            media.Source = new Uri(_listMedia[_currentIndex].src);
            cboList.SelectedIndex = _currentIndex;
        }
        /**/
        /// <summary>
        /// 下拉列表改变时，播放相关片段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _currentIndex = cboList.SelectedIndex;
            if (_currentIndex > _listMedia.Count - 1)
            {
                _currentIndex = 0;
            }
            media.Source = new Uri(_listMedia[_currentIndex].src);
            canvas_Pause.Visibility = System.Windows.Visibility.Collapsed;
            media.Position = new TimeSpan(0, 0, 0, 0, 0);
            sliderProgress.Value = 0;
        }
        /**/
        /// <summary>
        /// 暂时Canvas点击后，隐藏Canvas，同时继续播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Canvas_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            canvas_Pause.Visibility = System.Windows.Visibility.Collapsed;
            media.Play();
        }
        /**/
        /// <summary>
        /// 视频画面单击时，暂时播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void media_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            canvas_Pause.Visibility = System.Windows.Visibility.Visible;
            media.Pause();
        }
        /**/
        /// <summary>
        /// 进度条拖动时，跳到相关位置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sliderProgress_ValueChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
        {
            this.media.Position = new TimeSpan((long)(e.NewValue * 1000 * 1000 * 10));
        }

        //private void media_BufferingProgressChanged(object sender, RoutedEventHandler e) 
        //{
        //    txtTime.Text = "缓冲中" + media.BufferingProgress.ToString("F0") + "%";
        //}
        /**/
        /// <summary>
        /// 静音按钮的实现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVoice_Click(object sender, RoutedEventArgs e)
        {
            if (media.IsMuted)
            {
                media.IsMuted = false;
                this.btnVoice.Content = "静";
                sliderVoice.IsEnabled = true;
            }
            else
            {
                media.IsMuted = true;
                this.btnVoice.Content = "音";
                sliderVoice.IsEnabled = false;
            }
        }
        /**/
        /// <summary>
        /// 调整音量大小
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sliderVoice_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (sliderVoice == null)
            {
                return;
            }
            media.Volume = sliderVoice.Value;
        }
        private void btnFull_Click(object sender, RoutedEventArgs e)
        {
            Content contentObj = Application.Current.Host.Content;
            contentObj.IsFullScreen = !contentObj.IsFullScreen;

        }

        private void Content_FullScreenChanged(object sender, EventArgs e)
        {
            Content contentObj = Application.Current.Host.Content;

            if (contentObj.IsFullScreen)
            {
                btnFull.Content = "退";
            }
            else
            {
                btnFull.Content = "全";
            }
        }
        /**/
        /// <summary>
        /// 显示缓冲进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void media_BufferingProgressChanged(object sender, RoutedEventArgs e)
        {
            this.txtProgress.Text = "缓冲中" + (media.BufferingProgress * 100).ToString("F0") + "%";
            canvas_Pause.Visibility = Visibility.Visible;
            if (media.BufferingProgress >= 1.0)
            {
                canvas_Pause.Visibility = Visibility.Collapsed;
                switch (media.CurrentState)
                {
                    case System.Windows.Media.MediaElementState.Buffering:
                        txtProgress.Text = "缓冲中";
                        break;
                    case System.Windows.Media.MediaElementState.Closed:
                        txtProgress.Text = "已关闭";
                        break;
                    case System.Windows.Media.MediaElementState.Paused:
                        txtProgress.Text = "已暂停";
                        break;
                    case System.Windows.Media.MediaElementState.Playing:
                        txtProgress.Text = "正在播放";
                        break;
                    case System.Windows.Media.MediaElementState.Stopped:
                        txtProgress.Text = "已停止";
                        break;
                    default:
                        txtProgress.Text = "就绪";
                        break;
                }
            }
        }
        /**/
        /// <summary>
        /// 显示加载进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void media_DownloadProgressChanged(object sender, RoutedEventArgs e)
        {
            txtProgress.Text = "加载中" + (media.DownloadProgress * 100).ToString("F0") + "%";
            if (media.DownloadProgress >= 1)
            {
                switch (media.CurrentState)
                {
                    case System.Windows.Media.MediaElementState.Buffering:
                        txtProgress.Text = "缓冲中";
                        break;
                    case System.Windows.Media.MediaElementState.Closed:
                        txtProgress.Text = "已关闭";
                        break;
                    case System.Windows.Media.MediaElementState.Paused:
                        txtProgress.Text = "已暂停";
                        break;
                    case System.Windows.Media.MediaElementState.Playing:
                        txtProgress.Text = "正在播放";
                        break;
                    case System.Windows.Media.MediaElementState.Stopped:
                        txtProgress.Text = "已停止";
                        break;
                    default:
                        txtProgress.Text = "就绪";
                        break;
                }
            }
        }

    }

    /**/
    /// <summary>
    /// 媒体元素Item自定义类
    /// </summary>
    public class MediaItem
    {
        public string src { set; get; }
        public string name { set; get; }
    }
}
